<?php
/**
 * Created by PhpStorm.
 * User: ycbwl
 * Date: 2018/10/27
 * Time: 3:01 PM
 */
namespace app\api\service;


use app\lib\exception\TokenException;
use think\Exception;
use think\facade\Cache;
use think\facade\Request;

class Token{

    public static function generateToken(){
        //32个字符组成一组无意义的随机字符串
        $randchars = getRandChars(32);
        //用三组字符串，进行md5加密
        $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
        //salt 盐
        $salt = config("secure.token_salt");
        return md5($randchars.$timestamp.$salt);
    }

    public static function getCurrentTokenVar($key){
        $token = Request::instance()->header('token');
        $vars = Cache::get($token);
        if(!$vars){
            throw new TokenException();
        }else{
            if(!is_array($vars)){
                $vars = json_decode($vars,true);
            }
            if(array_key_exists($key,$vars)){
                return $vars[$key];
            }else{
                throw new Exception('尝试获取的Token变量并不存在！');
            }
        }
    }


    public static function getCurrentUid(){
        $uid = self::getCurrentTokenVar('uid');
        return $uid;
    }

    public static function verifyToken($token){
        $exist = Cache::get($token);
        if($exist){
            return true;
        }else{
            return false;
        }
    }


    public static function isValidOperate($checkUID){
        if(!$checkUID){
            throw new Exception('检查UID时候必须传入一个被检查的UID');
        }
        $currentUID =  \app\lib\Token::getDataForToken('id','mini');
        if($currentUID == $checkUID){
            return true;
        }
        return false;
    }

}